//
//  LLGEmoticonToolBar.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/18.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

//区分按钮
enum LLGEmoticonToolBarButtonType: Int {

    //默认
    case Normal = 0
    //emoji
    case Emoji = 1
    //浪小花
    case LXH = 2
}

class LLGEmoticonToolBar: UIStackView {
    
    //点击按钮闭包
    var didSelectedButtonClosure: ((type: LLGEmoticonToolBarButtonType) -> ())?
    
    var lastSelectedButton: UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: --添加控件,设置约束
    private func setupUI() {
        
        //水平布局
        axis = .Horizontal
        //等比填充
        distribution = .FillEqually
    
        addChildButton("默认", imageName: "compose_emotion_table_left", type: .Normal)
        addChildButton("Emoji", imageName: "compose_emotion_table_mid", type: .Emoji)
        addChildButton("浪小花", imageName: "compose_emotion_table_right", type: .LXH)
        
    }
    
    // MARK: --添加按钮
    private func addChildButton(title: String, imageName: String, type: LLGEmoticonToolBarButtonType) {
    
        let button = UIButton()
        
        //获取枚举的原始值,设置tag
        button.tag = type.rawValue
        
        //添加点击事件
        button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        
        button.setTitle(title, forState: .Normal)
        //设置不同状态下的文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
        
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "\(imageName)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "\(imageName)_selected"), forState: .Selected)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        //取消高亮
        button.adjustsImageWhenHighlighted = false
        
        addArrangedSubview(button)
    }
    
    // MARK: --点击事件
    @objc private func buttonAction(button: UIButton) {
        
        if lastSelectedButton == button {
            return
        }
        
        lastSelectedButton?.selected = false
        
        button.selected = true
        
        lastSelectedButton = button
        //根据原始值获取枚举值
        let type = LLGEmoticonToolBarButtonType(rawValue: button.tag)!
        //按钮闭包执行
        didSelectedButtonClosure?(type: type)
    }

    
}
